package org.jeecg.modules.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.wms.entity.WmsMaterialWarningLog;
import org.jeecg.modules.wms.service.IWmsMaterialWarningLogService;
import org.jeecg.modules.wms.service.IWmsPurchaseOrderService;
import org.jeecg.modules.wms.vo.WmsMaterialWarningVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 物料预警管理
 * @Author: jeecg-boot
 * @Date: 2023-07-17
 * @Version: V1.0
 */
@Api(tags="物料预警管理")
@RestController
@RequestMapping("/wms/purchase/warning")
@Slf4j
public class WmsMaterialWarningController extends JeecgController<WmsMaterialWarningLog, IWmsMaterialWarningLogService> {
    @Autowired
    private IWmsMaterialWarningLogService wmsMaterialWarningLogService;
    
    @Autowired
    private IWmsPurchaseOrderService wmsPurchaseOrderService;
    
    /**
     * 分页列表查询
     *
     * @param wmsMaterialWarningLog
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "物料预警-分页列表查询")
    @ApiOperation(value="物料预警-分页列表查询", notes="物料预警-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmsMaterialWarningVO>> queryPageList(WmsMaterialWarningLog wmsMaterialWarningLog,
                                                      @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                      HttpServletRequest req) {
        Map<String, Object> queryParam = new HashMap<>();
        
        // 处理物料编码和名称查询
        if (wmsMaterialWarningLog.getMaterialCode() != null) {
            queryParam.put("materialCode", wmsMaterialWarningLog.getMaterialCode());
        }
        if (wmsMaterialWarningLog.getMaterialName() != null) {
            queryParam.put("materialName", wmsMaterialWarningLog.getMaterialName());
        }
        
        // 处理物料类型
        String materialType = req.getParameter("materialType");
        if (StringUtils.isNotEmpty(materialType)) {
            queryParam.put("materialType", materialType);
        }
        
        // 处理预警类型
        if (wmsMaterialWarningLog.getWarningType() != null) {
            queryParam.put("warningType", wmsMaterialWarningLog.getWarningType());
        }
        
        // 处理处理状态
        if (wmsMaterialWarningLog.getHandled() != null) {
            queryParam.put("handled", wmsMaterialWarningLog.getHandled());
        }
        
        Page<WmsMaterialWarningVO> page = new Page<>(pageNo, pageSize);
        IPage<WmsMaterialWarningVO> pageList = wmsMaterialWarningLogService.queryWarningPageList(page, queryParam);
        
        return Result.OK(pageList);
    }
    
    /**
     * 刷新物料预警
     *
     * @return
     */
    @AutoLog(value = "物料预警-刷新预警")
    @ApiOperation(value="物料预警-刷新预警", notes="物料预警-刷新预警")
    @PostMapping(value = "/refresh")
    public Result<?> refreshWarnings() {
        return wmsMaterialWarningLogService.refreshWarnings();
    }
    
    /**
     * 标记预警为已处理
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料预警-标记已处理")
    @ApiOperation(value="物料预警-标记已处理", notes="物料预警-标记已处理")
    @PostMapping(value = "/markHandled")
    public Result<?> markHandled(@RequestParam(name="id") String id, HttpServletRequest request) {
        String username = JwtUtil.getUserNameByToken(request);
        return wmsMaterialWarningLogService.markWarningHandled(id, username);
    }
    
    /**
     * 根据ID获取预警详情
     *
     * @param params
     * @return
     */
    @AutoLog(value = "物料预警-根据ID获取详情")
    @ApiOperation(value="物料预警-根据ID获取详情", notes="物料预警-根据ID获取详情")
    @PostMapping(value = "/getByIds")
    public Result<List<WmsMaterialWarningVO>> getWarningsByIds(@RequestBody Map<String, Object> params) {
        String idsStr = (String) params.get("ids");
        if (StringUtils.isEmpty(idsStr)) {
            return Result.error("请提供预警记录ID");
        }
        
        List<String> ids = Arrays.asList(idsStr.split(","));
        List<WmsMaterialWarningVO> warnings = wmsMaterialWarningLogService.selectWarningsByIds(ids);
        return Result.OK(warnings);
    }
    
    /**
     * 根据预警生成采购计划
     *
     * @param params
     * @return
     */
    @AutoLog(value = "物料预警-生成采购计划")
    @ApiOperation(value="物料预警-生成采购计划", notes="物料预警-生成采购计划")
    @PostMapping(value = "/generatePurchase")
    public Result<?> generatePurchase(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        String supplier = (String) params.get("supplier");
        String expectedArrivalDate = (String) params.get("expectedArrivalDate");
        String remark = (String) params.get("remark");
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> details = (List<Map<String, Object>>) params.get("details");
        
        if (details == null || details.isEmpty()) {
            return Result.error("请选择需要处理的预警记录");
        }
        
        if (StringUtils.isEmpty(supplier)) {
            return Result.error("请输入供应商");
        }
        
        try {
            // 提取预警ID列表
            List<String> warningIds = details.stream()
                .map(detail -> (String) detail.get("warningId"))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
            
            if (warningIds.isEmpty()) {
                return Result.error("未找到有效的预警记录ID");
            }
            
            // 调用采购单服务生成采购计划 - 使用正确的参数类型
            Result<?> result = wmsPurchaseOrderService.generatePurchaseOrderFromWarnings(warningIds, supplier);
            
            if (result.isSuccess()) {
                // 更新预警记录为已处理
                String purchaseOrderId = (String) result.getResult();
                if (purchaseOrderId != null) {
                    wmsMaterialWarningLogService.batchUpdatePurchaseOrderId(warningIds, purchaseOrderId);
                }
            }
            
            return result;
        } catch (Exception e) {
            log.error("生成采购计划失败", e);
            return Result.error("生成采购计划失败: " + e.getMessage());
        }
    }
    
    /**
     * 导出excel
     *
     * @param request
     * @param wmsMaterialWarningLog
     * @return
     */
    @AutoLog(value = "物料预警-导出")
    @ApiOperation(value="物料预警-导出", notes="物料预警-导出")
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmsMaterialWarningLog wmsMaterialWarningLog) {
        return super.exportXls(request, wmsMaterialWarningLog, WmsMaterialWarningLog.class, "物料预警");
    }
} 